import { ProList } from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
  DrawerForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormUploadDragger,
} from '@ant-design/pro-form';
import { Button, Card, Space, Tag } from 'antd';
import { useRef, useState } from 'react';
import { queryProduct } from '../service';

export type FormValueType = {
  keyword?: number;
  channel?: string;
  products?: [];
};
/**
 * 获取热销商品名称列表
 * @param data 商品数据数组
 * @param topN 可选参数，指定返回前N个热销商品
 * @returns 返回按订单量排序的商品信息数组，包含商品名称、评分和订单量
 */

export type RobotProductFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: any) => Promise<void>;
  visible: boolean;
  values?: any;
};

const RobotProductForm: React.FC<RobotProductFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [keyword, setKeyword] = useState('');
  const [commands, setCommands] = useState([]);

  const labels = [
    '食品',
    '女装',
    '内衣裤袜',
    '男装',
    '护肤',
    '彩妆',
    '饮品',
    '童装',
    '婴童',
    '个护',
    '女鞋',
    '保健',
    '家居用品',
    '家电',
    '宠物',
    '饰品',
    '海鲜水产',
    '服饰配件',
    '数码',
  ];
  const fillTypes = [
    { label: '全部', value: 3 },
    { label: '商品', value: 1 },
    { label: '口令', value: 2 },
  ];
  const categories = labels.map((label, index) => ({
    label,
    value: index + 1, // 从 1 开始
  }));
  const [cates] = useState(categories);
  return (
    <DrawerForm
      title="爆品合集"
      width={620}
      formRef={formRef}
      visible={props.visible}
      onVisibleChange={(visible) => {
        if (!visible) {
          props.onCancel(false);
          setCommands([]);
          formRef?.current?.setFieldsValue({
            queryword: '',
          });
        } else {
          formRef?.current?.setFieldsValue({
            rate: props?.values.rate,
            cate: props?.values.cate,
            keyword: props?.values.keyword,
            fillType: props?.values.type,
          });
        }
      }}
      onFinish={async (values) => {
        // return;
        const item = cates.find((item) => item.value === values.cate);

        if (props.values.id) {
          await props.onSubmit({ ...values, id: props.values.id, cate: item?.label });
          return true;
        }

        await props.onSubmit({ ...values, cate: item?.label });
        return true;
      }}
      initialValues={props.values}
    >
      <ProForm.Group>
        <ProFormText
          name="queryword"
          width="md"
          placeholder="请输入关键词"
          onChange={(e) => {
            setKeyword(e.target.value);
          }}
        />
        <Button
          type="primary"
          onClick={async () => {
            const rsp = await queryProduct({ keyword });
            if (rsp.code === 'SUCCESS') {
              setCommands(rsp.data);
            }
          }}
        >
          获取
        </Button>
      </ProForm.Group>
      <ProList<any>
        rowKey="id"
        headerTitle="商品列表"
        dataSource={commands}
        metas={{
          title: {
            dataIndex: 'productName',
          },
          description: {
            render: (_, record) => {
              const item = cates.find((item) => item.value === record.cate);
              return (
                <>
                  <Space size="small">
                    <Tag color="blue">后台佣金: {record.rate}</Tag>
                    <Tag color="green">分类: {item?.label}</Tag>
                  </Space>
                </>
              );
            },
          },
          extra: {
            render: (_, record) => (
              <Button
                type="primary"
                onClick={async () => {
                  formRef?.current?.setFieldsValue({
                    rate: record.rate / 100,
                    keyword: record.productName,
                  });
                }}
              >
                使用
              </Button>
            ),
          },
        }}
      />
      <Card title="商品详情" style={{ marginTop: 24 }} bordered={false}>
        <ProForm.Group>
          <ProFormText name="keyword" label="关键词" width="sm" placeholder="请输入关键词" />
          <ProFormSelect name="cate" label="分类" options={cates} />
          <ProFormSelect name="fillType" label="抓取类型" options={fillTypes} />
          <ProFormDigit name="rate" label="佣金" placeholder="请输入佣金" />
        </ProForm.Group>
        <ProFormUploadDragger
          name="file"
          label="上传文件"
          max={1}
          fieldProps={{
            name: 'file',
            action: '/api/uploadDyFileCommandDiff',
          }}
        ></ProFormUploadDragger>
      </Card>
    </DrawerForm>
  );
};

export default RobotProductForm;
